from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from ..database import get_db
from ..models.user import User
from ..auth.jwt_handler import get_current_user
from .auth import get_password_hash, verify_password

router = APIRouter(
    prefix='/user',  # 移除/api
    tags=['user'],
)

# 忘记密码请求
@router.post('/forgot-password')
def forgot_password(
    email_data: dict,  # 使用字典接收请求体
    db: Session = Depends(get_db)
):
    email = email_data.get('email')
    if not email:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='Email is required'
        )
    
    user = db.query(User).filter(User.email == email).first()
    if not user:
        # 即使用户不存在，也返回成功消息，以防止枚举攻击
        return {'message': 'If the email exists, a password reset link has been sent'}
    
    # 这里应该添加发送重置密码邮件的逻辑
    # 为了简单起见，我们只返回成功消息
    return {'message': 'If the email exists, a password reset link has been sent'}

# 重置密码
@router.post('/reset-password')
def reset_password(
    reset_data: dict,  # 使用字典接收请求体
    db: Session = Depends(get_db)
):
    token = reset_data.get('token')
    new_password = reset_data.get('password')
    
    if not token or not new_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='Token and password are required'
        )
    
    # 这里应该验证token的逻辑
    # 为了简单起见，我们假设token是有效的，并找到第一个用户
    # 实际应用中应该有一个专门的token表来存储重置密码的token
    user = db.query(User).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='User not found'
        )
    
    # 更新密码
    user.password = get_password_hash(new_password)
    db.commit()
    
    return {'message': 'Password has been reset successfully'}

# 更新密码
@router.post('/update-password')
def update_password(
    password_data: dict,  # 使用字典接收请求体
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    current_password = password_data.get('currentPassword')
    new_password = password_data.get('newPassword')
    
    if not current_password or not new_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='Current password and new password are required'
        )
    
    # 验证当前密码
    if not verify_password(current_password, current_user.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail='Current password is incorrect'
        )
    
    # 更新密码
    current_user.password = get_password_hash(new_password)
    db.commit()
    
    return {'message': 'Password has been updated successfully'}

# 更新邮箱
@router.post('/update-email')
def update_email(
    email_data: dict,  # 使用字典接收请求体
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    new_email = email_data.get('email')
    if not new_email:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='Email is required'
        )
    
    # 检查新邮箱是否已被使用
    existing_user = db.query(User).filter(User.email == new_email).first()
    if existing_user and existing_user.id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='This email is already in use'
        )
    
    # 更新邮箱
    current_user.email = new_email
    db.commit()
    
    return {'message': 'Email has been updated successfully'}